<?php

namespace app\index\controller;

use app\Request;

// use Fiber;
use GuzzleHttp\Client;
/* use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Utils;
use React\EventLoop\Factory;
use support\Log;
use GuzzleHttp\TransferStats; */
use app\common\StreamResponse;
use Webman\Http\Response;
use Psr\Http\Message\StreamInterface;
use GuzzleHttp\Psr7\Stream;

class IndexController
{
    public function index(Request $request)
    {
        if ($request->method() == "POST") {
            $all = $request->all();

            $client = new Client([
                "headers" => [
                    "Host" => "lemurchat.anfans.cn",
                    "User-Agent" => "Mozilla/5.0 (Linux;Android 13;22021211RC) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/110.0.0.0 MobileSafari/537.36"
                ],
            ]);

            $response = $client->request(
                'POST',
                'http://lemurchat.anfans.cn:80/api/chat/conversation-trial',
                [
                    'stream' => true,
                    "json" => [
                        "messages" => json_encode([
                            [
                                "content" => "",
                                "id" => "LEMUR_AI_SYSTEM_SETTING",
                                "isSensitive" => false,
                                "needCheck" => false,
                                "role" => "system"
                            ],
                            [
                                "content" => $all["msg"],
                                "isSensitive" => false,
                                "needCheck" => true,
                                "role" => "user"
                            ]
                        ], 320)
                    ],
                    'progress' => function ($bytesTransferred, $size) use (&$fileSize) {
                        $fileSize = $size; // 更新已传输的总字节数
                    }
                ]
            );

            $api = $response->getBody();
            // return $api;
            // 创建一个空的 Response 对象
            $res = new Response();

            // 设置响应头
            $res->withHeader('Content-Type', 'application/json');

            // 创建一个新的 StreamInterface 对象并写入数据
            $body = new Stream(fopen('php://temp', 'r+'));

            $i = $fileSize;
            $str = "";
            while (!$api->eof()) {
                $str .= $api->read(1);
                if ($i != $fileSize && $i > 200) {
                    $arr = GptData($str);
                    foreach ($arr as $k => $v) {
                        $body->write(json_encode($v, 320));
                    }
                    $str = "";
                }
                $i = $fileSize;
            }
            // 设置 Response 对象的 body 内容
            $res->withBody($body);

            return $res;

            /* // 开启输出响应体数据
            ob_start();
            $i = $fileSize;
            $str = "";
            while (!$body->eof()) {
                $str .= $body->read(1);
                if ($i != $fileSize && $i > 200) {
                    $arr = GptData($str);
                    foreach ($arr as $k => $v) {
                        return json_encode($v, 320);

                        flush(); //输出到客户端
                    }
                    $str = "";
                }
                $i = $fileSize;
            }
            ob_end_flush(); //结束
            return json(["success" => true]); */

            // 创建一个流式响应对象
            /* $res = StreamResponse::create(function ($stream) use (&$fileSize, $body) {
                $i = $fileSize;
                $str = "";
                while (!$body->eof()) {
                    $str .= $body->read(1);
                    if ($i != $fileSize && $i > 200) {
                        $arr = GptData($str);
                        foreach ($arr as $k => $v) {
                            $stream->write(json_encode($v, 320));
                        }
                        $str = "";
                    }
                    $i = $fileSize;
                }
            });

            return $res; */
        }

        return view("index/index");
    }
}
